/**
 * Created by Skye on 2018/3/29.
 */
import React, {Component} from 'react';
import {Modal, Form, Input, TreeSelect} from 'antd';
import axios from '../../../utils/axios';

const FormItem = Form.Item;
const formItemLayout = {
  labelCol: {
    span: 6,
  },
  wrapperCol: {
    span: 14,
  },
};

class AddDepartment extends Component {

  constructor(props) {
    super(props);
    this.state = {
      confirmLoading: false,
      parentDepartmentCode: null
    };
  }

  handleSubmit = (e) => {
    e.preventDefault();
    const { form } = this.props;
    form.validateFields(async(err, values) => {
      if (!err) {
        this.setState({
          confirmLoading: true,
        });
        const param = {
          departmentName: values.departmentName,
          parentDepartmentCode: this.state.parentDepartmentCode
        };
        const response = await axios.post('/api/rbac/mgmt/add-department', param);
        this.setState({
          confirmLoading: false,
        });
        const {success} = response.data;
        if (success) {
          form.resetFields();
          this.props.closeModal(true);
        }
      }
    });
  };

  handleSelect = (val) => {

    this.setState({
      parentDepartmentCode: val
    })
  };

  render() {
    const {getFieldDecorator} = this.props.form;
    const { departmentList } = this.props;
    return (
        <Modal title="添加部门"
               okText="确定"
               cancelText="取消"
               confirmLoading={this.state.confirmLoading}
               visible={this.props.visible}
               onOk={this.handleSubmit}
               onCancel={() => this.props.closeModal(false)}>
          <Form>
            <FormItem label="部门名称" { ...formItemLayout }>
              {getFieldDecorator('departmentName', {
                rules: [{required: true, message: '请输入部门名称'}],
              })(
                  <Input placeholder="部门名称"/>,
              )}
            </FormItem>
            <FormItem label="上级部门" { ...formItemLayout }>
              <TreeSelect
                  value={this.state.parentDepartmentCode}
                  dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                  treeData={departmentList}
                  placeholder="请选择上线部门，若不选择则添加为顶级总站"
                  treeDefaultExpandAll
                  onChange={this.handleSelect}
              />
            </FormItem>
          </Form>
        </Modal>
    );
  }
}

export default Form.create()(AddDepartment);